package com.jinlia.show.gateway.auth;

import cloud.tianai.captcha.common.constant.CaptchaTypeConstant;
import cloud.tianai.captcha.common.response.ApiResponse;
import cloud.tianai.captcha.spring.application.ImageCaptchaApplication;
import cloud.tianai.captcha.spring.vo.CaptchaResponse;
import cloud.tianai.captcha.spring.vo.ImageCaptchaVO;
import com.alibaba.fastjson.JSONObject;
import com.jinlia.show.gateway.vo.ImageCaptchaTrackVO;
import com.jinlia.show.gateway.vo.form.LoginRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Collections;
import java.util.concurrent.ThreadLocalRandom;

@RestController
//@RequiredArgsConstructor
public class AuthController {
//    final RedisUtils redisUtils;
    @Autowired
    AuthService authService;
    @Autowired
    ImageCaptchaApplication imageCaptchaApplication;

    /**
     * 用户登录
     */
    @PostMapping("token")
    public ResponseEntity<JSONObject> login(@RequestBody @Valid LoginRequest loginRequest) throws Exception {
        // 验证码判断
        JSONObject jsonObject = authService.builderToken(loginRequest);
        return ResponseEntity.ok(jsonObject);
    }
    @PostMapping("/auth/login")
    public ResponseEntity<JSONObject> token(@RequestBody @Valid LoginRequest loginRequest) throws Exception {
        // 验证码判断
        JSONObject jsonObject = authService.builderToken(loginRequest);
        return ResponseEntity.ok(jsonObject);
    }
    /**
     * 随机获取验证码
     *
     * @return
     */
    @RequestMapping("/get/captcha")
    public CaptchaResponse<ImageCaptchaVO> getCaptcha() {
        String type = null;
        int i = ThreadLocalRandom.current().nextInt(0, 4);
        if (i == 0) {
            type = CaptchaTypeConstant.SLIDER;
        } else if (i == 1) {
            type = CaptchaTypeConstant.CONCAT;
        } else if (i == 2) {
            type = CaptchaTypeConstant.ROTATE;
        } else {
            type = CaptchaTypeConstant.WORD_IMAGE_CLICK;
        }
        CaptchaResponse<ImageCaptchaVO> response = imageCaptchaApplication.generateCaptcha(type);
        return response;
    }

    @PostMapping("/check")
    public ApiResponse<?> checkCaptcha(@RequestBody ImageCaptchaTrackVO data) {
        ApiResponse<?> response = imageCaptchaApplication.matching(data.getId(), data.getData());
        if (response.isSuccess()) {
            return ApiResponse.ofSuccess(Collections.singletonMap("id", data.getId()));
        }
        return response;
    }

    @GetMapping("logout")
    public ResponseEntity<Boolean> login() {
        return ResponseEntity.ok(Boolean.TRUE);
    }
}
